<template>
  <div id="layout">
    <el-container style="height: 100%" :class="layoutSkin">
      <el-header>
        <img class="logo" src="../assets/logo.png" />
        <span class="compName">医顺达（山东）信息技术有限公司</span>
        <div class="win">
          <!-- <el-icon @click="">
            <Minus />
          </el-icon>
          <el-icon @click="">
            <CopyDocument />
          </el-icon>
          <el-icon @click="">
            <Close />
          </el-icon> -->
        </div>
      </el-header>
      <el-menu mode="horizontal" :default-active="activeMenu" :collapse="isCollapseMenu"
        :default-openeds="getDefaultOps()">
        <!-- 二级菜单，如果有三级菜单 -->
        <template v-for="(cmenu, idx) of menus" :key="cmenu.id">
          <el-sub-menu :index="idx + ''" v-if="cmenu.children && cmenu.children.length > 0">
            <template #title>
              <el-icon>
                <component :is="cmenu.icon" class="icon"></component>
              </el-icon>
              <span>{{ cmenu.title }}</span>
            </template>
            <!-- 三级菜单 -->
            <el-menu-item :index="idx + '-' + cidx" v-for="(ccmenu, cidx) of cmenu.children" :key="ccmenu.id"
              @click="selectThirdMenu(ccmenu, childMenus)">{{ ccmenu.title }}</el-menu-item>
          </el-sub-menu>
          <!-- 二级菜单，没有三级菜单 -->
          <el-menu-item v-else :index="idx + ''" @click="selectThirdMenu(cmenu, childMenus)">{{
            cmenu.title
          }}</el-menu-item>
        </template>
      </el-menu>
      <el-container style="height: calc(100% - 40px)">
        <el-aside width="50px">
          <!-- <div
            :class="['menu', { 'active-menu': menu.selected }]"
            v-for="menu of menus"
            :key="menu.id"
            @click="selectFirstMenu(menu)"
          >
            <el-icon>
              <component :is="menu.icon" class="icon"></component>
            </el-icon>
            <span>{{ menu.title }}</span>
          </div> -->

          <!-- 左侧导航栏 -->
          <el-menu text-color="" default-active="1" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose">
            <el-menu-item v-for="(item, index) in menus" :key="index" :index="item.order" @click="selectFirstMenu(item)">
              <el-icon><icon-menu /></el-icon>
              <span>{{ item.title }}</span>
            </el-menu-item>
          </el-menu>

          <div class="bottom-menu">
            <div class="menu">
              <el-icon @click="foldSecMenu">
                <Expand v-if="isCollapseMenu" />
                <Fold v-else />
              </el-icon>
            </div>
            <div class="menu">
              <el-popover placement="right" title="我的主题" :width="220" trigger="click">
                <template #reference>
                  <el-icon>
                    <Menu />
                  </el-icon>
                </template>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <div class="slt-skin" @click="changeLayoutSkin('skin-blue')">
                      <el-container class="skin-blue">
                        <el-header></el-header>
                        <el-container>
                          <el-aside width="10px"></el-aside>
                          <el-main></el-main>
                        </el-container>
                      </el-container>
                      <span>蓝色主题</span>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="slt-skin" @click="changeLayoutSkin('skin-black')">
                      <el-container class="skin-black">
                        <el-header></el-header>
                        <el-container>
                          <el-aside width="10px"></el-aside>
                          <el-main></el-main>
                        </el-container>
                      </el-container>
                      <span>黑色主题</span>
                    </div>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <div class="slt-skin" @click="changeLayoutSkin('skin-gray')">
                      <el-container class="skin-gray">
                        <el-header></el-header>
                        <el-container>
                          <el-aside width="10px"></el-aside>
                          <el-main></el-main>
                        </el-container>
                      </el-container>
                      <span>灰色主题</span>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="slt-skin" @click="changeLayoutSkin('skin-green')">
                      <el-container class="skin-green">
                        <el-header></el-header>
                        <el-container>
                          <el-aside width="10px"></el-aside>
                          <el-main></el-main>
                        </el-container>
                      </el-container>
                      <span>绿色主题</span>
                    </div>
                  </el-col>
                </el-row>
              </el-popover>
            </div>
            <div class="menu">
              <el-icon @click="gotoDemo">
                <HelpFilled />
              </el-icon>
              <!-- <el-popover placement="right" :width="220" trigger="click">
                <template #reference>
             <el-icon @click="gotoTest">
                    <HelpFilled />
                  </el-icon>     
                </template>
              </el-popover> -->
            </div>
            <div class="menu">
              <el-popover placement="right" :width="100" trigger="click">
                <template #reference>
                  <el-icon>
                    <UserFilled />
                  </el-icon>
                </template>
                <ul class="menu-ul">
                  <li>
                    <el-button text plain icon="Lock" @click="showChangePassword">修改密码</el-button>
                  </li>
                  <li><el-button text plain icon="User">修改信息</el-button></li>
                  <li>
                    <el-button text plain icon="SwitchButton" @click="logout">退出系统</el-button>
                  </li>
                  <li>
                    <el-button text plain icon="SwitchButton" @click="testVxeTable">测试</el-button>
                  </li>
                </ul>
              </el-popover>
            </div>
          </div>
        </el-aside>
        <el-main>
          <el-container v-if="childMenus && childMenus.length > 0" style="height: 100%">
            <el-main>
              <RouterView />
            </el-main>
          </el-container>
          <RouterView v-else />
        </el-main>
      </el-container>
    </el-container>
    <el-dialog class="dia-update" v-model="showUpdater" title="下载更新" width="300" align-center
      :close-on-click-modal="false" :close-on-press-escape="false">
      <span class="title">发现了新版本，正在下载更新</span>
      <el-progress type="dashboard" :percentage="percentage" :color="colors">
        <template #default="{ percentage }">
          <span>{{ percentage }}%</span>
        </template>
      </el-progress>
    </el-dialog>
    <DialogPassword ref="digPwd" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted, provide, readonly } from 'vue';
import { AppStore } from '../stores/store';
// import { ElMessageBox } from 'element-plus';
import { notifyType, notifyMessage } from '../utils/common';
// import { io } from 'socket.io-client';
import DialogPassword from '../components/DialogPassword.vue';
import getLodop from '../lib/lodop';

let { proxy }: any = getCurrentInstance();
let store = AppStore();
// let socket = io('ws://localhost:' + proxy.$electronConfig.LOCAL_SOCKET_PORT, {
//   withCredentials: true
// });

let layoutSkin = ref('skin-blue');
const menus: any = reactive([]);
const childMenus: any = reactive([]);
let activeMenu = ref('');

let isCollapseMenu = ref(false); //是否折叠，默认否
provide('isCollapseMenu', readonly(isCollapseMenu)); //根级父组件提供是否收起的数据，子组件根据此数据判断其是否要调整自身宽度样式

let showUpdater = ref(false);
let percentage = ref(0);
const colors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#6f7ad3', percentage: 100 }
];
// let conHeight = ref(
//   (document.documentElement.clientHeight || document.body.clientHeight) - 40 + 'px'
// );
let digPwd: any = ref(null);

onMounted(async () => {
  if (!store.userInfo) {
    proxy.$router.push('/login');
    return;
  }
  if (store.userInfo.layoutSkin) {
    layoutSkin.value = store.userInfo.layoutSkin;
  }
  //获取用户角色、菜单和权限列表
  findRolePers();
  //获取部门
  findDept();
  //获取系统字典
  findDictionaryList();
  //获取默认打印机
  findDefaultPrinter();
});

// function initSocketClient() {
//   const socket = io('ws://localhost:10001', { withCredentials: true });
//   // send a message to the server
//   socket.emit('hello from client', 5, '6', { 7: Uint8Array.from([8]) });
//   // receive a message from the server
//   socket.on('hello from server', (...args) => {
//     console.log(args);
//     // ...
//   });
// }

//获取用户角色权限
function findRolePers() {
  proxy.$http
    .get('/api/user/findUserRoleMenuPermissionList', {
      params: {
        userId: store.userInfo.id
      }
    })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
        return;
      }
      if (res.data.roleMenuPmsList && res.data.roleMenuPmsList.length > 0) {
        store.setRolePermission(res.data.roleMenuPmsList[0].permissionList);
        store.setRoleMenu(res.data.roleMenuPmsList[0].menuTree);
        store.setRole(res.data.roleMenuPmsList[0].roleId);

        //设置左侧菜单
        for (const item of res.data.roleMenuPmsList[0].menuTree) {
          const temp = {
            id: item.id,
            title: item.title,
            url: item.url,
            icon: item.icon,
            selected: false,
            order: item.order,
            children: item.children
          };
          menus.push(temp);
        }
        if (menus.length > 0) {
          //判断当前路由是否有数据，如果有则加载当前路由的路径菜单，否则加载默认
          if (proxy.$router.currentRoute.value && proxy.$router.currentRoute.value.fullPath) {
            //找到路径，定位
            childMenus.length = 0;
            const temp = findRouterPathMenu(proxy.$router.currentRoute.value.fullPath, menus, 0);
            if (temp.idxStr && temp.idxStr.length > 0) {
              activeMenu.value = temp.idxStr;
            }
          } else {
            menus[0].selected = true;
            //绑定二级菜单
            if (menus[0].children && menus[0].children.length > 0) {
              //添加二级菜单
              childMenus.push(...menus[0].children);
              if (childMenus[0].children && childMenus[0].children.length > 0) {
                //默认打开三级菜单
                activeMenu.value = '0-0'; //childMenus[0].children[0].id;
                proxy.$router.push(childMenus[0].children[0].url);
              } else {
                //打开二级页面
                activeMenu.value = '0'; // childMenus[0].id;
                proxy.$router.push(childMenus[0].url);
              }
            } else {
              //打开一级页面
              proxy.$router.push(menus[0].url);
            }
          }
        }
      }
    })
    .catch((err: string) => {
      notifyMessage(err, notifyType.warning, proxy);
    });
}

function findRouterPathMenu(path: string, menuList: any, level: number, idx?: any) {
  let idxStr = '';
  if (idx >= 0) {
    idxStr += idx + '';
  }
  let result = false;
  const temp = menuList.findIndex((p: any) => p.url === path);
  if (temp >= 0) {
    if (level === 0) {
      menuList[temp].selected = true;
    } else {
      idxStr += '-' + temp + '';
    }
    result = true;
  } else {
    let idx = 0;
    for (const item of menuList) {
      if (item.children && item.children.length > 0) {
        const flag = findRouterPathMenu(path, item.children, level + 1, idx);
        if (flag.result === true) {
          result = true;
          if (level > 1 && idxStr.length > 0) {
            idxStr += '-' + flag.idxStr + '';
          } else {
            idxStr = flag.idxStr;
          }
          if (level === 0) {
            childMenus.push(...item.children);
            item.selected = true;
          }
          break;
        } else {
          result = false;
        }
      }
      idx++;
    }
  }
  return { result, idxStr };
}

function findDept() {
  proxy.$http
    .get('/api/user/findUserDepts', { params: { userId: store.userInfo.id } })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
        return;
      } else if (res.data.userDepts.length === 0) {
        notifyMessage('请联系系统管理员，添加用户部门信息', notifyType.warning, proxy);
        return;
      } else {
        const dept = res.data.userDepts[0].Department;
        const obj = {
          deptId: dept ? dept.id : '',
          deptName: dept ? dept.name : '',
          deptCode: dept ? dept.code : ''
        };
        store.setUserCurDept(obj);
        store.setUserDepts(res.data.userDepts.map((p: any) => p.Department));
      }
    })
    .catch((err: string) => {
      notifyMessage('获取部门信息错误：' + err, notifyType.warning, proxy);
    });
}

async function findDictionaryList() {
  // const temp: any = new Object();
  // temp.macAddress = Value;
  // //获取系统字典
  // // const urlDict = '/api/sys/findAllDictionaryList';
  // // const resDict: any = await proxy.$http.get(urlDict, {
  // //   params: { orgId: store.userInfo.orgId }
  // // });
  // // if (resDict.status.code === 1) {
  // //   for (const dict of resDict.data.dictList) {
  // //     temp[dict.key] = dict.value;
  // //   }
  // // }
  // // //获取本机字典
  // const url = '/api/sys/findDictionaryLocalByMacAddr';
  // const resLocal: any = await proxy.$http.get(url, { params: { macAddress: Value } });
  // if (resLocal.status.code === 1) {
  //   for (const dict of resLocal.data.dictList) {
  //     temp[dict.key] = dict.value;
  //   }
  //   that.setSysDict(temp);
  // }
  // store.setSysDict(temp);
}

function findDefaultPrinter() {
  if (!store.printer || !store.printer.defaultName) {
    // socket.emit('wsGetDefaultPrinter', (res) => {
    //   if (res && res.status.code === 1) {
    //     let temp = {
    //       defaultName: res.data.printer.name,
    //       paperSize: 'A4',
    //       silentPrint: 0
    //     };
    //     store.setPrinter(temp);
    //   }
    // });
  }
}

//选择一级菜单
function selectFirstMenu(menu: any) {
  menu.selected = true;
  menus.forEach((p: any) => {
    if (p.title != menu.title && p.selected) {
      p.selected = false;
    }
  });
  childMenus.length = 0;
  if (menu.children && menu.children.length > 0) {
    //如果有子菜单，打开第一个子菜单
    childMenus.push(...menu.children);
    if (childMenus[0].children && childMenus[0].children.length > 0) {
      //如果第一个子菜单还有子菜单，则打开第一个子子菜单：三级菜单
      activeMenu.value = '0-0';
      proxy.$router.push(childMenus[0].children[0].url);
    } else {
      //如果第一个子菜单没有子菜单，则直接打开：二级页面
      activeMenu.value = '0';
      proxy.$router.push(childMenus[0].url);
    }
  } else {
    //如果没有子菜单，则直接打开
    proxy.$router.push(menu.url);
  }
}
function getDefaultOps() {
  if (childMenus && childMenus.length > 0) {
    return ['0'];
  } else {
    return [];
  }
}
//选择三级菜单
function selectThirdMenu(curMenu: any, curMenus: any) {
  curMenu.selected = true;
  curMenus.forEach((p: any) => {
    if (p.title != curMenu.title && p.selected) {
      p.selected = false;
    }
  });
  proxy.$router.push(curMenu.url);
}

//收起-弹开二级菜单
function foldSecMenu() {
  isCollapseMenu.value = !isCollapseMenu.value;
}
//换肤
function changeLayoutSkin(skin: any) {
  layoutSkin.value = skin;
  const postData = {
    id: store.userInfo.id,
    layoutSkin: skin
  };

  let url = '/api/user/editUserSimple';
  proxy.$http
    .post(url, postData)
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      }
    })
    .catch((err: string) => {
      notifyMessage(err, notifyType.warning, proxy);
    });
}
//弹出修改密码框
function showChangePassword() {
  digPwd.value?.showChangePassword();
}
//退出
function logout() {
  proxy
    .$confirm('确定退出本系统?', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      // //关闭消息连接
      // if (socketIO) {
      //   socketIO.disconnect();
      // }
      // if (warningNotifyList.length > 0) {
      //   warningNotifyList.forEach((item: any) => {
      //     if (item) {
      //       item.close();
      //     }
      //   });
      // }
      let url = '/public/user/LoginOut';
      proxy.$http
        .post(url)
        .then((res: any) => {
          // console.log('退出登录',res)
        })
        .catch((err: string) => {
          notifyMessage(err, notifyType.warning, proxy);
        });

      store.setSignOut();
      proxy.$router.push('/login');
    })
    .catch(() => {
      console.log('cancel logout');
    });
}

function gotoDemo() {
  proxy.$router.push('/demo');
}
function testVxeTable() {
  proxy.$router.push('/testvxetable');
}
</script>
<style lang="scss" scoped>
@import '../assets/css/layout.scss';

#layout {
  height: 100%;

  .el-header {
    height: 40px !important;
    width: 100%;
    line-height: 40px;
    position: relative;

    .logo {
      height: 25px;
      width: 25px;
      position: absolute;
      left: 15px;
      top: 50%;
      transform: translateY(-50%);
    }

    .compName {
      position: absolute;
      left: 50px;
      font-size: 14px;
    }

    .win {
      position: absolute;
      right: 10px;

      .el-icon {
        margin-top: 5px;
        padding: 8px;
        border-radius: 5px;
        cursor: pointer;
      }
    }
  }

  .el-aside {
    text-align: center;

    .menu {
      margin: 0;
      padding: 10px 0;
      cursor: pointer;

      i {
        font-size: 20px;
      }

      span {
        display: block;
        font-size: 12px;
      }

      .el-badge__content {
        height: 15px;
        line-height: 15px;
        padding: 0 4px;
      }

      .el-badge__content.is-fixed {
        right: 7px;
      }
    }

    .bottom-menu {
      position: absolute;
      bottom: 10px;

      .menu {
        width: 50px;
      }
    }
  }

  .el-main {
    // text-align: center;
    padding: 0;

    //background-color: $bg-content;
    .menu-children {
      background-color: $bg-white;
      transition: width 300ms ease-in-out;

      // border-right: $border-4;
      .el-menu {
        height: 100%;
        --el-menu-base-level-padding: 13px !important;
        --el-menu-item-height: 59px;

        .el-sub-menu {
          border-bottom: $border-4;
        }

        .el-menu-item {
          background-color: $bg-disable;
        }

        .el-menu-item.is-active {
          background-color: $brand-color;
          color: $base-white;
        }
      }

      .el-menu--collapse {
        width: 50px !important;
        --el-menu-base-level-padding: 13px !important;
        --el-menu-item-height: 59px;
      }
    }

    :deep(.el-scrollbar__view) {
      height: 100%;
    }
  }

  .dia-update {
    text-align: center;

    .title {
      margin-bottom: 15px;
      display: block;
    }
  }

  // --el-menu-base-level-padding: 13px;
  .el-aside {
    width: 200px;
  }
}
</style>
